package showAll;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.codec.binary.Base64;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;

import pojo.User;
import dao.impl.UserDaoImpl;

/**
 * Servlet implementation class ShowAllServlet
 */
public class ShowAllServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ShowAllServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		UserDaoImpl udi=new UserDaoImpl();
		List<User> list=new ArrayList<User>();
		list=udi.getAll();
		response.setHeader("Content-Type", "text/html");
		
		StringBuilder dom = new StringBuilder();
		dom.append("<table border=\"1\">");
		dom.append("<tr><th>UserName</th><th>birth</th><th>salary</th><th>sex</th><th>portrait</th></tr>");
		for (User u : list) {
			dom.append("<tr><th>"+ u.getName() +"</th><th>"+u.getBirth() +"</th><th>"+ u.getSal() +"</th><th>");
			if (u.isSex()) {
				dom.append("Male"+"</th></tr>");
			}else {
				dom.append("Female"+"</th></tr>");
			}
			dom.append("<th><img src=" + byte2Base64StringFun(u.getPortait())+ " style=\"width:100px,height:100px\"></img></th>");
		}
		dom.append("</table>");
		
		response.getWriter().write(dom.toString());

	}
	
	public String byte2Base64StringFun(byte[] b) {
		return "data:image/png;base64," + Base64.encodeBase64String(b);
	}
	

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
